from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship
from datetime import datetime
from ..database import Base

# 账号和环境的多对多关联表
account_environment = Table(
    'account_environment',
    Base.metadata,
    Column('account_id', Integer, ForeignKey('accounts.id')),
    Column('environment_id', Integer, ForeignKey('environments.id'))
)

class Account(Base):
    __tablename__ = "accounts"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)
    wechat_id = Column(String, unique=True, index=True)
    password = Column(String)
    status = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关联环境
    environments = relationship(
        "Environment",
        secondary=account_environment,
        back_populates="accounts"
    )

class Environment(Base):
    __tablename__ = "environments"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True)
    browser_id = Column(String, unique=True, index=True)
    status = Column(Boolean, default=True)
    remarks = Column(String, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关联账号
    accounts = relationship(
        "Account",
        secondary=account_environment,
        back_populates="environments"
    )